package cuit.demo.controller;

import cuit.demo.Entity.Article;
import cuit.demo.Entity.Comment;
import cuit.demo.Entity.User;
import cuit.demo.service.MyService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.List;

@Controller
public class ArticleController {

    @Autowired
    private MyService myService;

    // 根据文章 ID 获取文章详细信息及评论并展示在 article.html 页面
    @GetMapping("/article/{id}")
    public String getArticle(@PathVariable int id, Model model,HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(user != null) {
            Article article = myService.findArticleById(id);
            model.addAttribute("article", article);
            // 获取文章的评论列表
            List<Comment> comments = myService.findCommentsByArticleId(id);
            model.addAttribute("comments", comments);
            return "article";
        }else{
            return "login";
        }
    }

    @PostMapping("/addComment/{articleId}")
    public String addComment(@PathVariable int articleId,
                             @RequestParam("comment_text") String comment_text,
                             HttpSession session) {
        User user = (User) session.getAttribute("user");
        Comment newComment = new Comment();
        newComment.setComment_text(comment_text);
        newComment.setArticle_id(articleId);
        newComment.setUserid(user.getUserid());
        newComment.setCreatetime(String.valueOf(LocalDateTime.now()));
        newComment.setCommenter(user.getUsername());
        myService.saveComment(newComment);
        return "redirect:/article/" + articleId;
    }

    @GetMapping("/deleteComment/{commentId}")
    public String deleteComment(@PathVariable int commentId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Comment comment = myService.findCommentById(commentId);
        if (comment!= null && comment.getUserid()==(user.getUserid())) {
            myService.deleteComment(commentId);
        }
        return "redirect:/article/" + comment.getArticle_id();
    }

    @GetMapping("/downloadAttachment/{articleId}")
    public void downloadAttachment(@PathVariable int articleId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        File attachmentFile = myService.getArticleAttachment(articleId);
        if (attachmentFile!= null && attachmentFile.exists()) {
            String fileName = attachmentFile.getName();
            // 设置响应头，告诉浏览器这是一个文件下载，而不是普通的页面浏览
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 读取文件内容并写入到输出流，发送给浏览器
            FileInputStream fis = new FileInputStream(attachmentFile);
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer))!= -1) {
                os.write(buffer, 0, length);
            }
            fis.close();
            os.close();
        } else {
            // 如果文件不存在，你可以根据需求返回一个错误页面或者在前端显示相应的提示信息
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "附件不存在");
        }
    }
}